package com.zt.weibo.database;

import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import com.zt.weibo.utils.FormatString;
import com.zt.weibo.utils.PrintLog;
import com.zt.weibo.utils.WeiboCons;

/**
 * 该类封装了对数据库增删改查的方法。是线程安全的。
 * @author zhaotong
 */
public class WeiboDatabaseMgr
{
	private static WeiboDatabaseMgr instance = null;
	private WeiboDatabaseOpenHelper mOpenHelper = null;
	private SQLiteDatabase	mDatabase = null;
	
	public synchronized static WeiboDatabaseMgr getInstance(Context con)
	{
		if(null == instance)
		{
			instance = new WeiboDatabaseMgr(con);
		}
		return instance;
	}
	
	/**
	 * 关闭数据库。程序彻底结束时调用。
	 */
	public void closeDB()
	{
		synchronized (mDatabase)
		{
			if(mDatabase.isOpen())
			{
				mDatabase.close();
			}
		}
	}
	
	private WeiboDatabaseMgr(Context con)
	{
		mOpenHelper = new WeiboDatabaseOpenHelper(con);
		mDatabase = mOpenHelper.getWritableDatabase();
	}
	
	/**
	 * 增加一个用户的授权信息
	 * @param username 用户名
	 * @param accesstoken 授权后获得的AccessToken
	 * @param expiresin 授权后获得的ExpiresIn，即AccessToken有效时间字符。
	 * <p>在函数中经过换算，得到AccessToken过期的时间，单位为秒。
	 * @return 新加入的行号。-1表示出错。
	 */
	public long insertOauthInfo(String username, String accesstoken, String expiresin)
	{
		int invalidtime = FormatString.formatInvalidTime(expiresin);
		ContentValues values = new ContentValues();
		values.put(WeiboCons.DB_USER_NAME, username);
		values.put(WeiboCons.DB_ACCESS_TOKEN, accesstoken);
		values.put(WeiboCons.DB_EXPIRES_IN, expiresin);
		values.put(WeiboCons.DB_INVALID_DATE, invalidtime);
		try
		{
			synchronized(mDatabase)
			{
				PrintLog.debug("增加了用户授权信息：" + username + "\n" + accesstoken + 
						"\n" + expiresin + "\n" + invalidtime);
				return (int) mDatabase.insert(WeiboCons.DB_TABLE, null, values);
			}
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
			return -1;
		}
	}
	
	/**
	 * 根据给定用户名查询AccessToken字符串。
	 * @param username
	 * @return AccessToken
	 */
	public String queryAccessToken(String username)
	{
		String str = null;
		Cursor cursor = null;
		try
		{
			synchronized (mDatabase)
			{
				cursor =  mDatabase.query(WeiboCons.DB_TABLE, new String[]{WeiboCons.DB_ACCESS_TOKEN},
						WeiboCons.DB_USER_NAME + " = '" + username + "'", null, null, null, null);
			}
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
			cursor.close();
			return null;
		}
		if(cursor.moveToFirst())
		{
			str = cursor.getString(cursor.getColumnIndex(WeiboCons.DB_ACCESS_TOKEN));
		}
		cursor.close();
		return str;
	}
	
	/**
	 * 根据用户名查询ExpiresIn字符
	 * @param username
	 * @return ExpiresIn
	 */
	public String queryExpiresIn(String username)
	{
		String str = "";
		Cursor cursor = null;
		try
		{
			synchronized (mDatabase)
			{
				cursor = mDatabase.query(WeiboCons.DB_TABLE, new String[]{WeiboCons.DB_EXPIRES_IN}, 
						WeiboCons.DB_USER_NAME + " = '" + username + "'", null, null, null, null);			
			}
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
			cursor.close();
			return null;
		}
		if(cursor.moveToFirst())
		{
			str = cursor.getString(cursor.getColumnIndex(WeiboCons.DB_EXPIRES_IN));
		}
		cursor.close();
		return str;
	}
	
	/**
	 * 根据给定用户名查询AccessToken的过期日期。
	 * @param username 用户名
	 * @return 过期日期。单位为秒。失败为-1。
	 */
	public int queryInvalidDate(String username)
	{
		int i = 0;
		Cursor cursor = null;
		try
		{
			synchronized (mDatabase)
			{
				cursor = mDatabase.query(WeiboCons.DB_TABLE, new String[]{WeiboCons.DB_INVALID_DATE}, 
						WeiboCons.DB_USER_NAME + " = '" + username + "'", null, null, null, null);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			cursor.close();
			return -1;
		}
		if(cursor.moveToFirst())
		{
			i = cursor.getInt(cursor.getColumnIndex(WeiboCons.DB_INVALID_DATE));
		}
		cursor.close();
		return i;
	}
	
	/**
	 * 查询数据库中是否存在该用户。对大小写不敏感。
	 * @param username 用户名
	 * @return true or false
	 */
	public boolean isUserExist(String username)
	{
		boolean b = false;
		String str = null;
		Cursor cursor = null;
		try
		{
			synchronized (mDatabase)
			{
				cursor = mDatabase.query(WeiboCons.DB_TABLE, new String[]{WeiboCons.DB_USER_NAME}, 
						null, null, null, null, null);			
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			cursor.close();
			return false;
		}
		if(cursor.moveToFirst())
		{
			for(int i = 0; i < cursor.getCount(); i ++)
			{
				cursor.moveToPosition(i);
				str = cursor.getString(cursor.getColumnIndex(WeiboCons.DB_USER_NAME));
				PrintLog.debug("行数 " + i + ", UserName is " + str);
				if(username.toLowerCase().equals(str.toLowerCase()))
				{
					PrintLog.debug("Already Find User");
					b = true;
					break;
				}
				else
				{
					continue;
				}
			}
		}
		cursor.close();
		return b;
	}
	
	/**
	 * 更新该用户的授权信息
	 * @param username 用户名
	 * @param accesstoken AccessToken字符串
	 * @param expiresin 授权后获得的ExpiresIn，即AccessToken有效时间。
	 * <p>在函数中经过换算，得到AccessToken过期的时间，单位为秒。
	 * @return 失败返回-1
	 */
	public int updateOauthInfo(String username, String accesstoken, String expiresin)
	{
		int invalidtime = FormatString.formatInvalidTime(expiresin);
		ContentValues values = new ContentValues();
		values.put(WeiboCons.DB_USER_NAME, username);
		values.put(WeiboCons.DB_ACCESS_TOKEN, accesstoken);
		values.put(WeiboCons.DB_EXPIRES_IN, expiresin);
		values.put(WeiboCons.DB_INVALID_DATE, invalidtime);
		try
		{
			synchronized (mDatabase)
			{
				PrintLog.debug("更新了用户授权信息：" + username + "\n" + accesstoken + 
						"\n" + expiresin + "\n" + invalidtime + "\n");
				return mDatabase.update(WeiboCons.DB_TABLE, values, 
						WeiboCons.DB_USER_NAME + "='" + username + "'", null);
			}
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
			return -1;
		}
	}
	
	/**
	 * 删除该用户的授权信息。
	 * @param username 用户名
	 * @return 失败返回-1
	 */
	public int deletOauthInfo(String username)
	{
		try
		{
			synchronized (mDatabase)
			{
				return mDatabase.delete(WeiboCons.DB_TABLE, WeiboCons.DB_USER_NAME + 
						" = '" + username + "'", null);
			}
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
			return -1;
		}
	}
	
	/**
	 * 获取所有登陆过的用户名。
	 * @return 存有所有用户名的List，失败返回null。
	 */
	public ArrayList<String> getAllUsers()
	{
		ArrayList<String> mUsers = new ArrayList<String>();
		Cursor cursor = null;
		try
		{
			synchronized (mDatabase)
			{
				cursor = mDatabase.query(WeiboCons.DB_TABLE, new String[]{WeiboCons.DB_USER_NAME},
						null, null, null, null, null);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			cursor.close();
			return null;
		}
		if(cursor.moveToFirst())
		{
			for(int i = 0; i < cursor.getCount(); i ++)
			{
				cursor.moveToPosition(i);
				mUsers.add(cursor.getString(cursor.getColumnIndex(WeiboCons.DB_USER_NAME)));
			}
		}
		else
		{
			mUsers = null;
		}
		cursor.close();
		return mUsers;
	}
	
	/**
	 * 将指定用户名的数据在数据库中的位置提前到首位。
	 * @param username 需要提前到首位的用户
	 * @return 成功返回true，失败返回false
	 */
	public synchronized boolean moveToFirst(String username)
	{
		ArrayList<ContentValues> values = new ArrayList<ContentValues>();
		Cursor cursor = null;
		int iUserPos = 0;
		try
		{
			mDatabase.beginTransaction();
			cursor = mDatabase.query(WeiboCons.DB_TABLE, null,
					null, null, null, null, null);
			if (cursor.moveToFirst())
			{
				for (int i = 0; i < cursor.getCount(); i ++)
				{
					cursor.moveToPosition(i);
					ContentValues value = new ContentValues();
					value.put(WeiboCons.DB_USER_NAME, cursor.getString(cursor.getColumnIndex(
							WeiboCons.DB_USER_NAME)));
					value.put(WeiboCons.DB_ACCESS_TOKEN, cursor.getString(cursor.getColumnIndex(
							WeiboCons.DB_ACCESS_TOKEN)));
					value.put(WeiboCons.DB_EXPIRES_IN, cursor.getString(cursor.getColumnIndex(
							WeiboCons.DB_EXPIRES_IN)));
					value.put(WeiboCons.DB_INVALID_DATE, cursor.getString(cursor.getColumnIndex(
							WeiboCons.DB_INVALID_DATE)));
					values.add(value);
					PrintLog.debug("排序前，第" + i + "行：" + value.toString());
					if (value.getAsString(WeiboCons.DB_USER_NAME).equals(username))
					{
						iUserPos = i;
						if (0 == iUserPos)
						{
							PrintLog.debug("已经在第一位");
							cursor.close();
							return true;
						}
					}
				}
			}
			cursor.close();
			values.add(0, values.get(iUserPos));
			values.remove(iUserPos + 1);
			mDatabase.delete(WeiboCons.DB_TABLE, null, null);
			for (int i = 0; i < values.size(); i ++)
			{
				ContentValues value = values.get(i);
				mDatabase.insert(WeiboCons.DB_TABLE, null, value);
				PrintLog.debug("排序后，第" + i + "行：" + value.toString());
			}
			mDatabase.setTransactionSuccessful();
			return true;
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
			cursor.close();
			return false;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			cursor.close();
			return false;
		} finally {
			mDatabase.endTransaction();
		}
	}
	
}
